package Component;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.*;

public class ImagePanel extends JPanel {

	private static final long serialVersionUID = 6903178695927693629L;
	private Image image;
    private Image scaledImage;
    private int imageWidth = 0;
    private int imageHeight = 0;

    //constructor
    public ImagePanel() {
        super();
    }

    public void loadImage(String file) throws IOException {
        image = ImageIO.read(new File(file));
        
        imageWidth = image.getWidth(this);
        imageHeight = image.getHeight(this);
        
        setScaledImage();
    }

    public void scaleImage() {
        setScaledImage();
    }

    //override paintComponent
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if ( scaledImage != null ) {
            g.drawImage(scaledImage, 0, 0, this);
        }
    }

    private void setScaledImage() {
        if ( image != null ) {

            float iw = imageWidth;
            float ih = imageHeight;
            float pw = this.getWidth();   //panel width
            float ph = this.getHeight();  //panel height

            //to preserve image ratio
            if ( (pw / ph) > (iw / ih) ) {
                iw = -1;
                ih = ph;
            } else {
                iw = pw;
                ih = -1;
            }

            //prevent errors if panel is 0 wide or high
            if (iw == 0) {
                iw = -1;
            }
            if (ih == 0) {
                ih = -1;
            }

            scaledImage = image.getScaledInstance(
                        new Float(iw).intValue(), new Float(ih).intValue(), Image.SCALE_DEFAULT);
        }
    }

}